package 剑指offer_专项突破版;

public class Num001 {
    //整数除法
    public int divide(int a, int b) {
        if(a == 0x80000000 && b == -1){
            //(-2^31)/(-1)这个情况得到的证书会发生栈溢出
            return java.lang.Integer.MAX_VALUE;
        }
        int flag = 2;  //标志位，看被除数和除数中正负情况

        //正数全改成复数，因为整数比负数少一位，预防溢出
        if(a > 0){
            flag--;
            a = -a;
        }
        if(b > 0){
            flag--;
            b = -b;
        }

        int result = divideCore(a,b);

        return flag == 1 ? -result : result;//返回正确的正负
    }

    private int divideCore(int a,int b){
        int result = 0;
        while(a <= b){
            int value = b;
            int quotient = 1;
            while(value >= 0xc0000000 && a <= value +value){
                quotient += quotient;
                value += value;
            }
            result +=quotient;
            a -= value;
        }
        return result;
    }
}
